package com.yin.myproject.zk.WatcherSample;

import com.yin.myproject.zk.client.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Eason on 2017/8/7.
 */
public class WatcherClient {
    public static void main(String[] args) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String path = "/task/node/192.168.0.1";
                    CuratorFramework zkClient1 = ZkClient.getNewZkClient();
                    zkClient1.start();
                    Stat stat = zkClient1.checkExists().forPath(path);
                    if (stat != null) {
                        zkClient1.delete().forPath(path);
                    }
                    zkClient1.create().withMode(CreateMode.EPHEMERAL).forPath("/task/node/192.168.0.1");
                    zkClient1.getData().usingWatcher(new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            System.out.println("***********************************");
                            System.out.println("WatchedEvent path-->" + event.getPath());
                            System.out.println("WatchedEvent type" + event.getType().toString());
                        }
                    }).forPath(path);
                    zkClient1.checkExists().forPath(path);
                    zkClient1.setData().forPath(path,"123".getBytes());
                    zkClient1.getData().usingWatcher(new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            System.out.println("***********************************");
                            System.out.println("WatchedEvent path-->" + event.getPath());
                            System.out.println("WatchedEvent type" + event.getType().toString());
                        }
                    }).forPath(path);
                    zkClient1.delete().forPath(path);
                    zkClient1.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
